import protoRoot from '@/proto/proto'

export function isArrayBuffer(obj) {
  return Object.prototype.toString.call(obj) === '[object ArrayBuffer]'
}

/**
 * 将protobuf blob转json，查找rule数据
 * @param raw
 * @param rule
 * @returns object
 */
export function transformProtoBufResponse(raw: Blob, rule: string): Promise<Object> {
  return new Promise((resolve) => {
    if (raw === null || !(raw instanceof Blob)) {
      resolve(raw)
      return
    }
    const reader: any = new FileReader()
    reader.readAsArrayBuffer(raw)
    reader.onload = () => {
      const buf = new Uint8Array(reader.result)
      const model: any = protoRoot.lookup(rule)
      const data = model.decode(buf)
      resolve(data)
    }
  })
}
/**
 * 返回proto定义的enum数据
 * @param rule
 * @returns object
 */
export function getProtoBufEnum(rule: string): Object {
  return protoRoot.lookupEnum(rule)
}
/**
 * 返回proto定义的enum数据
 * @param rule
 * @returns object
 */
export function getProtoBufType(rule: string): Object {
  return protoRoot.lookupType(rule)
}
